package com.tlgen.modules.drugstore.service.impl;

import com.tlgen.common.exception.EntityExistException;
import com.tlgen.common.utils.FileUtil;
import com.tlgen.common.utils.PageUtil;
import com.tlgen.common.utils.QueryHelp;
import com.tlgen.common.utils.ValidationUtil;
import com.tlgen.modules.drugstore.domain.MedicinalData;
import com.tlgen.modules.drugstore.repository.MedicinalDataRepository;
import com.tlgen.modules.drugstore.service.MedicinalDataService;
import com.tlgen.modules.drugstore.service.dto.MedicinalDataDto;
import com.tlgen.modules.drugstore.service.dto.MedicinalDataQueryCriteria;
import com.tlgen.modules.drugstore.service.mapper.MedicinalDataMapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Service
@CacheConfig(cacheNames = "MedicinalData")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MedicinalDataServiceImpl implements MedicinalDataService {

    private final MedicinalDataRepository medicinalDataRepository;

    private final MedicinalDataMapper medicinalDataMapper;

    public MedicinalDataServiceImpl(MedicinalDataRepository medicinalDataRepository, MedicinalDataMapper medicinalDataMapper) {
        this.medicinalDataRepository = medicinalDataRepository;
        this.medicinalDataMapper = medicinalDataMapper;
    }

    /**
     * 根据登记人员名称获取信息
     * @param name
     * @return
     */
    @Override
    @Cacheable(key = "'loadUserByName:'+#p0")
    public MedicinalDataDto findByName(String name) {
        MedicinalData medicinalData1;
        medicinalData1 = medicinalDataRepository.findByMedicinalName(name);
        if(medicinalData1==null){
            throw new EntityExistException(MedicinalData.class,"MedicinalData",name);
        }else {
            return medicinalDataMapper.toDto(medicinalData1);
        }
    }

    /**
     * 不带条件分页查询
     * @param pageable 分页参数
     * @return
     */
    @Override
    @Cacheable
    public Object queryAll(Pageable pageable) {
        return medicinalDataMapper.toDto(medicinalDataRepository.findAll(pageable).getContent());
    }


    /**
     * 带条件分页查询
     * @param criteria 条件
     * @param pageable 分页参数
     * @return
     */
    @Override
    @Cacheable
    public Object queryAll(MedicinalDataQueryCriteria criteria, Pageable pageable) {
        Page<MedicinalData> page = medicinalDataRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(medicinalDataMapper::toDto));
    }

    /**
     * 带条件不分页查询
     * @param criteria 条件
     * @return
     */
    @Override
    @Cacheable
    public List<MedicinalDataDto> queryAll(MedicinalDataQueryCriteria criteria) {
        return medicinalDataMapper.toDto(medicinalDataRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    /**
     * 新增
     * @param resources /
     * @return
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public MedicinalDataDto create(MedicinalData resources) {
        if (medicinalDataRepository.findByMedicinalName(resources.getMedicinalName()) != null) {
            throw new EntityExistException(MedicinalData.class, "MedicinalData", resources.getMedicinalName());
        }
        return medicinalDataMapper.toDto(medicinalDataRepository.save(resources));
    }

    /**
     * 编辑
     * @param resources /
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(MedicinalData resources) {
        MedicinalData medicinalData = medicinalDataRepository.findById(resources.getId()).orElseGet(MedicinalData::new);
        ValidationUtil.isNull(medicinalData.getId(),"MedicinalData","id",resources.getId());

        medicinalData.setMedicinalName(resources.getMedicinalName());
        medicinalData.setMedicinalAgent(resources.getMedicinalAgent());
        medicinalData.setUnit(resources.getUnit());
        medicinalData.setPrice(resources.getPrice());
        medicinalData.setUnit(resources.getUnit());
        medicinalData.setMedicinalPlace(resources.getMedicinalPlace());
        medicinalData.setProductDate(resources.getProductDate());
        medicinalData.setLimitDate(resources.getLimitDate());
        medicinalData.setBatchNumber(resources.getBatchNumber());
        medicinalData.setMedicinalMainSort(resources.getMedicinalMainSort());
        medicinalData.setMedicinalSort(resources.getMedicinalSort());
        medicinalData.setMedicinalType(resources.getMedicinalType());
        medicinalData.setMedicinalAmount(resources.getMedicinalAmount());
        medicinalDataRepository.save(medicinalData);
    }

    /**
     * 删除
     * @param ids /
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        for (Long id : ids) {
            medicinalDataRepository.deleteById(id);
        }
    }

    /**
     * 导出数据
     * @param response /
     * @throws IOException
     */
    @Override
    public void download(List<MedicinalDataDto> medicinalDataDtos, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (MedicinalDataDto medicinalDataDto : medicinalDataDtos) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("药名", medicinalDataDto.getMedicinalName());
            map.put("经办人", medicinalDataDto.getMedicinalAgent());
            map.put("单位", medicinalDataDto.getUnit());
            map.put("价格", medicinalDataDto.getPrice());
            map.put("产地", medicinalDataDto.getMedicinalPlace());
            map.put("生产日期", medicinalDataDto.getProductDate());
            map.put("有效日期", medicinalDataDto.getLimitDate());
            map.put("批号", medicinalDataDto.getBatchNumber());
            map.put("药品分类", medicinalDataDto.getMedicinalSort().getMedicinalSortName());
            map.put("药品类型", medicinalDataDto.getMedicinalType());
            map.put("数量", medicinalDataDto.getMedicinalAmount());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 根据Id查询
     * @param id /
     * @return
     */
    @Override
    @Cacheable(key = "#p0")
    public MedicinalDataDto findById(long id) {
        MedicinalData MedicinalData = medicinalDataRepository.findById(id).orElseGet(MedicinalData::new);
        ValidationUtil.isNull(MedicinalData.getId(),"MedicinalData","id",id);
        return medicinalDataMapper.toDto(MedicinalData);
    }

}
